package splitting;

import java.io.*;

import org.junit.Test;

/**
 * This is the first step of splitting index file.
 * 
 * I read about 4KB of index file and then write it out.
 * 
 * I also test with GZIP, and it works fine. But then I switch back to raw
 * stream.
 * 
 * @author Genzer
 * 
 */

public class TestReadingAndWritingPartOfFile {

    private static final int SPLITTED_FILE_SIZE = 4 * 1024;
    private static final String INDEX_FILE = "C:/test/av.index";
    private static final String OUTPUT_FILE = "C:/test/outputFirstTest.txt";

    @Test
    public void testReadWithCustomeBuffer() {
        byte[] content = readContentIn();
        writeContentOut(content);       
    }

    private byte[] readContentIn() {
        byte[] buffer = new byte[SPLITTED_FILE_SIZE];
        
        FileInputStream reader = null;
        
        try {
            reader = new FileInputStream(INDEX_FILE);
            reader.read(buffer);
        } catch (FileNotFoundException fnf) {
            processException(fnf);
        } catch (IOException ioe) {
            processException(ioe);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                processException(e);
            }
        }
        
        return buffer;
    }
    
    
    private void writeContentOut(byte[] buffer) {
        FileOutputStream writer = null;
        
        try {
            writer = new FileOutputStream(OUTPUT_FILE);
            writer.write(buffer);
        } catch (FileNotFoundException fnf) {
            processException(fnf);
        } catch (IOException ioe) {
            processException(ioe);
        } finally {
            try {
                writer.close();
            } catch (IOException ioe) {
                processException(ioe);
            }
        }
    }

    private void processException(Exception exception) {
        throw new RuntimeException(exception);
    }

}
